<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="租户名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入租户名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="租户编号" prop="contact">
        <el-input
          v-model="queryParams.tenantId"
          placeholder="请输入租户编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系人" prop="contact">
        <el-input
          v-model="queryParams.contact"
          placeholder="请输入联系人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:tenant:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:tenant:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:tenant:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:tenant:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tenantList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="租户ID" align="center" prop="id" v-if="false"/>
      <el-table-column label="租户名称" align="center" prop="name" />
      <el-table-column label="租户编号" align="center" prop="tenantId" />
      <el-table-column label="联系人" align="center" prop="contact" />
      <el-table-column label="电话" align="center" prop="phone" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:tenant:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:tenant:remove']"
          >删除</el-button>

          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['system:tenant:buyModule']">
                <span class="el-dropdown-link">
                  <i class="el-icon-d-arrow-right el-icon--right"></i>更多
                </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleModule" icon="el-icon-circle-check"
                                v-hasPermi="['system:tenant:buyModule']">模块购买</el-dropdown-item>

            </el-dropdown-menu>
          </el-dropdown>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改租户管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-input v-model="form.id" v-if="false"/>
        <el-form-item label="租户名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入租户名称" />
        </el-form-item>
        <el-form-item label="联系人" prop="contact">
          <el-input v-model="form.contact" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 租户模块管理对话框 -->
    <el-dialog title="租户模块购买" :visible.sync="buyOpen" width="700px" append-to-body>
      <el-table
        :data="tableData"
        border
        style="width: 100%" >
        <el-table-column
          prop="moduleName"
          label="模块名称">
        </el-table-column>

        <el-table-column
          prop="endTime"
          label="原到期时间"  :formatter="endTimeShowData">
        </el-table-column>

        <el-table-column
          prop="buyTime"
          label="购买时长">
          <template slot-scope="scope">
            <el-select  :ref="scope.row.id" v-model="scope.row.buyTime" placeholder="请选择" @change="buyTimeShowEndTime(scope.row)">
              <el-option
                v-for="item in dict.type.tenant_buy_time"
                :key="item.value"
                :label="item.label"
                :value="item.value" >
              </el-option>
            </el-select>
          </template>
        </el-table-column>

        <el-table-column
          prop="buyEndTime"
          label="购买后到期时间" >
        </el-table-column>

      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buyButtonLoading" type="primary" @click="submitBuyForm">确 定</el-button>
        <el-button @click="cancelBuy">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTenant, getTenant, delTenant, addTenant, updateTenant ,getBusinessModuleByTenantId,addBuyModule } from "@/api/system/tenant";
import moment from 'moment'
export default {
  name: "Tenant",
  dicts: ['tenant_buy_time'],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 购买确定按钮loading
      buyButtonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 租户管理表格数据
      tenantList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示模块购买弹出层
      buyOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        contact: undefined,
        phone: undefined,
        name: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        contact: [
          { required: true, message: "联系人不能为空", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          { required: true, pattern: /^1[3|5|7|8|9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'change' }
        ],
        name: [
          { required: true, message: "租户名称不能为空", trigger: "blur" }
        ]
      },
      tableData: []
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询租户管理列表 */
    getList() {
      this.loading = true;
      listTenant(this.queryParams).then(response => {
        this.tenantList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        remark: undefined,
        tenantId: undefined,
        contact: undefined,
        phone: undefined,
        name: undefined,
        userId: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加租户管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getTenant(id).then(response => {
        this.loading = false;
        debugger
        this.form = response.data;
        this.open = true;
        this.title = "修改租户管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateTenant(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addTenant(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('删除租户后租户对应的全部用户将被删除,是否确认？').then(() => {
        this.loading = true;
        return delTenant(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/tenant/export', {
        ...this.queryParams
      }, `tenant_${new Date().getTime()}.xlsx`)
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleModule":
          this.handleModule(row);
          break;
        default:
          break;
      }
    },
    handleModule(row){
      this.buyOpen = true
      this.form.tenantId = row.tenantId;
      // TODO 根据租户id 获取模块数据
      getBusinessModuleByTenantId(row.tenantId).then(response => {
        this.tableData = response.data;
      })
    },
    submitBuyForm(){
      this.buyButtonLoading = true;
      let upData = [];
      for(let index in this.tableData){
        if(this.tableData[index].buyTime!=undefined){
          let json = {};
          json.id = this.tableData[index].tenantModuleId;
          json.moduleId = this.tableData[index].id;
          json.tenantId = this.form.tenantId;
          json.beginTime = moment(this.tableData[index].buyBeginTime).format("yyyy-MM-DD HH:ss:mm");
          json.endTime = moment(this.tableData[index].buyEndTime).format("yyyy-MM-DD HH:ss:mm");
          upData.push(json);
        }
      }
      if(upData.length==0){
        this.$modal.msgWarning("请至少购买一个模块");
        this.buyButtonLoading = false;
        return;
      }
      // 数据保存提交
      addBuyModule(upData).then(response => {
        this.$modal.msgSuccess("保存成功");
        this.buyOpen = false;
      });
      this.buyButtonLoading = false;

    },
    cancelBuy(){
      this.buyOpen = false
    },
    endTimeShowData(row, column, cellValue){
      if(row.endTime ==null){
        return "未购买";
      }else{
        return moment(row.endTime).format("yyyy-MM-DD");
      }
    },
    buyTimeShowEndTime(row){
      if(row.endTime ==null){
        // 当前时间加上购买时长
        row.buyEndTime = moment().add(row.buyTime, 'M').format('yyyy-MM-DD');
        row.buyBeginTime = moment().format("yyyy-MM-DD");
      }else{
        if(moment(row.endTime,"yyyy-MM-DD").diff(moment(),'days') >0){ // 结束时间大于现在的时间
            // 续买 到期时间加上购买时长
            row.buyEndTime = moment(row.endTime).add(row.buyTime, 'M').format('yyyy-MM-DD');
            row.buyBeginTime = moment(row.beginTime).format('yyyy-MM-DD');
        }else{
            // 当前时间加上购买时长
            row.buyEndTime = moment().add(row.buyTime, 'M').format('yyyy-MM-DD');
            row.buyBeginTime = moment().format("yyyy-MM-DD");
        }
      }
    }
  }
};
</script>
